/**
 * @file registry.cpp
 * @author Henrik Ojanen
 * @version 1.0
 * @date 6.4.2011
 */

#include <windows.h>
#include "registry.h"

namespace Rekisteri
{
	void LoadData(int* difficulty, int* color, int* highscore)
	{
		HKEY hKey;
		BYTE Data[3][sizeof(DWORD)];
		DWORD type = REG_DWORD;
		DWORD dwSize = sizeof(DWORD);

		RegCreateKeyEx(HKEY_CURRENT_USER, TEXT("Software\\Snake"), 0, NULL, 0, KEY_QUERY_VALUE, NULL, &hKey, NULL);

		RegQueryValueEx(hKey, TEXT("difficulty"), 0, &type, Data[0], &dwSize);
		RegQueryValueEx(hKey, TEXT("color"), 0, &type, Data[1], &dwSize);
		RegQueryValueEx(hKey, TEXT("highscore"), 0, &type, Data[2], &dwSize);

		if(difficulty != NULL)
			memcpy(difficulty, Data[0], dwSize);
		if(color != NULL)
			memcpy(color, Data[1], dwSize);
		if(highscore != NULL)
			memcpy(highscore, Data[2], dwSize);
	    
		RegCloseKey(hKey);
	}

	void SaveData(int difficulty, int color, int score)
	{
		HKEY hKey;
		BYTE Data[sizeof(DWORD)];
		DWORD type = REG_DWORD;
		DWORD dwSize = sizeof(DWORD);

		RegCreateKeyEx(HKEY_CURRENT_USER, TEXT("Software\\Snake"), 0, NULL, 0, KEY_ALL_ACCESS, NULL, &hKey, NULL);

		RegSetValueEx(hKey, TEXT("difficulty"), 0, type, (const BYTE*)&difficulty, dwSize);
		RegSetValueEx(hKey, TEXT("color"), 0, type, (const BYTE*)&color, dwSize);

		RegQueryValueEx(hKey, TEXT("highscore"), 0, &type, Data, &dwSize);
		if(score > *Data)
			RegSetValueEx(hKey, TEXT("highscore"), 0, type, (const BYTE*)&score, dwSize);

		RegCloseKey(hKey);
	}

	void ResetHighscore(int* ret)
	{
		HKEY hKey;
		int Data = 0;
		DWORD type = REG_DWORD;
		DWORD dwSize = sizeof(DWORD);

		RegCreateKeyEx(HKEY_CURRENT_USER, TEXT("Software\\Snake"), 0, NULL, 0, KEY_SET_VALUE, NULL, &hKey, NULL);

		RegSetValueEx(hKey, TEXT("highscore"), 0, type, (const BYTE*)&Data, dwSize);

		RegCloseKey(hKey);
	}
}
